package com.streamer.app

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.PixelFormat
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraManager
import android.os.Bundle
import android.util.Log
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import android.net.Uri
import android.widget.VideoView
import android.view.TextureView
import android.media.MediaPlayer
import android.view.Gravity
import android.widget.LinearLayout
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.viewpager2.widget.ViewPager2
import com.alivc.live.pusher.AlivcLivePusher
import com.bumptech.glide.Glide
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.streamer.app.bean.Item
import com.streamer.app.bean.LiveBean
import com.streamer.app.utils.DialogUtils
import com.streamer.app.utils.DialogUtils.showAnnouncementDialog
import com.streamer.app.utils.ToastUtil
import com.streamer.app.utils.UserManager.getLocalUser
import com.streamer.app.utils.api.ViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import androidx.core.net.toUri
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.streamer.app.adapter.ThreePanePagerAdapter
import com.streamer.app.bean.GiftData
import com.streamer.app.bean.MessageBean
import com.streamer.app.utils.MqttManager
import com.streamer.app.utils.UserManager
import com.streamer.app.utils.Utils
import com.streamer.app.utils.Utils.formatTime
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlin.random.Random

/**
 * 三分屏
 */
class ThreePaneLiveActivity : BaseActivity(), MqttManager.MessageCallback {

    private lateinit var cameraContainer: FrameLayout
    private lateinit var surfaceView: SurfaceView
    private lateinit var surfaceHolder: SurfaceHolder
    private lateinit var pauseOverlay: View
    private lateinit var tabLayout: TabLayout
    private lateinit var viewPager: ViewPager2
    private lateinit var ivAvatar: ImageView
    private lateinit var ivClose: ImageView
    private lateinit var tvStreamerName: TextView
    private lateinit var tvMessage: TextView
    private lateinit var tvStreamerNumber: TextView
    private var videoView: VideoView? = null // legacy, not used after switch
    private var mediaPlayer: MediaPlayer? = null
    private var viewMode = ViewModel()
    private var mliveData: LiveBean? = null
    private var isLiveStreaming = false
    private var pendingStartPush = false
    private var isCameraEnabled = true // 跟踪摄像头开关状态
    private var startOnNextLiveInfo: Boolean = false
    private lateinit var cameraOffBackground: ImageView
    private var currentState = State.PRE_LIVE // 当前状态
    private lateinit var llLiveNotice: LinearLayout
    private lateinit var centerEndedContent: LinearLayout
    private lateinit var userInfo: LinearLayout
    private lateinit var tvLiveStatus: TextView
    private val CAMERA_PERMISSION_REQUEST = 100
    private lateinit var mqttManager: MqttManager
    private lateinit var llGift: LinearLayout
    private lateinit var ivGiftIcon: ImageView
    private lateinit var tvGiftName: TextView
    // 风险提示文本相关
    private lateinit var riskAlertTextView: TextView
    private var riskAlertScrollJob: Job? = null
    private var riskAlertText = ""
    private var displayMode = 2 // 1:底部循环滚动, 2:全屏滚动
    private var displayFontSize = 14f
    private var displayFontColour = "#FFFFFF"
    private var displayScrollSpeed = 30 // 滚动速度(毫秒)
    private var displayTransparency = 0.8f // 透明度
    enum class State {
        NO_START_LIVE, PRE_LIVE,    // 开播
        LIVE_ENDED   // 直播结束
    }

    val mAlivcLivePusher = AlivcLivePusher()

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_three_pane_live)
        riskAlertTextView = findViewById(R.id.tv_risk_alert)

        // 初始化风险提示文本 - 使用 XML 中定义的 TextView
        llGift = findViewById(R.id.llGift)
        ivGiftIcon = findViewById(R.id.ivGiftIcon)
        tvGiftName = findViewById(R.id.tvGiftName)
        ivAvatar = findViewById(R.id.iv_streamer_avatar)
        ivClose = findViewById(R.id.ivClose)
        tvStreamerName = findViewById(R.id.tv_streamer_name)
        tvStreamerNumber = findViewById(R.id.tv_streamer_number)
        cameraContainer = findViewById(R.id.camera_container)
        tvMessage = findViewById(R.id.tv_message)
        tabLayout = findViewById(R.id.tab_layout)
        userInfo = findViewById(R.id.ll_user_info)
        tvLiveStatus = findViewById(R.id.tvLiveStatus)
        centerEndedContent = findViewById(R.id.center_ended_content)
        // 初始化SurfaceView - 使用普通SurfaceView实现全屏显示
        surfaceView = SurfaceView(this)
        surfaceHolder = surfaceView.holder
        // 提升渲染稳定性
        surfaceHolder.setFormat(PixelFormat.RGBA_8888)
        surfaceView.keepScreenOn = true

        viewPager = findViewById(R.id.view_pager)
        // Disable user swipe on ViewPager2 per requirement
        viewPager.isUserInputEnabled = false
        cameraOffBackground = findViewById(R.id.camera_off_background)
        llLiveNotice = findViewById(R.id.llLiveNotice)

        viewMode.getLiveData()
        viewMode.LiveInfoDataLV.observe(this@ThreePaneLiveActivity){
            if(it!=null){
                // Setup SurfaceView for camera
                viewPager.adapter = ThreePanePagerAdapter(this, it)
                TabLayoutMediator(tabLayout, viewPager) { tab, position ->
                    tab.text = when (position) {
                        0 -> "白板"
                        1 -> "聊天"
                        else -> "用户"
                    }
                }.attach()
            }
        }

        llLiveNotice.setOnClickListener {
            viewMode.getLastLiveNotice()
        }
        viewMode.LiveNoteTips.observe(this@ThreePaneLiveActivity) {
            if (it != null) {
                showAnnouncementDialog(this@ThreePaneLiveActivity, "公告", it.toString())
            }
        }
        ivAvatar.apply {
            Glide.with(this).load(getLocalUser()?.avatar).circleCrop().into(this)
            tvStreamerName.text = getLocalUser()?.nickName
        }
        surfaceHolder.addCallback(object : SurfaceHolder.Callback {
            override fun surfaceCreated(holder: SurfaceHolder) {
                Log.d("ThreePaneLiveActivity", "Surface created")
                // Surface创建后，若在直播中或等待启动，都强制先预览再推流，防止本地首帧卡住
                    try {
                    setExternalVideoSourceEnabled(false)
                    if (isLiveStreaming || pendingStartPush) {
                        Log.d("ThreePaneLiveActivity", "Calling startPreview(surfaceCreated)")
                        mAlivcLivePusher.startPreview(surfaceView)
                        surfaceView.postDelayed({
                            try {
                        if (!mliveData?.pushLiveUrl.isNullOrEmpty()) {
                                    Log.d(
                                        "ThreePaneLiveActivity", "Calling startPush(surfaceCreated)"
                                    )
                            mAlivcLivePusher.startPush(mliveData?.pushLiveUrl)
                        }
                            } catch (_: Exception) {
                            }
                        pendingStartPush = false
                        }, 150)
                    }
                } catch (_: Exception) {
                    pendingStartPush = false
                }
            }

            override fun surfaceChanged(
                holder: SurfaceHolder, format: Int, width: Int, height: Int
            ) {
                Log.d("ThreePaneLiveActivity", "Surface changed: ${width}x${height}")
                // 轻踢醒：Surface参数变更后，延时重启预览，降低黑屏/冻结概率
                surfaceView.postDelayed({
                    kickPreview()
                }, 150)
            }

            override fun surfaceDestroyed(holder: SurfaceHolder) {
                Log.d("ThreePaneLiveActivity", "Surface destroyed")
                // 安全停止预览以避免BufferQueue错误
                safeStopPreview()
            }
        })

        // 将SurfaceView添加到容器中
        cameraContainer.addView(surfaceView)

        // 设置SurfaceView的布局参数，实现全屏显示
        val layoutParams = FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
        )
        layoutParams.gravity = Gravity.CENTER
        surfaceView.layoutParams = layoutParams

        // 设置SurfaceView的ZOrder，确保摄像头预览在最上层
        surfaceView.setZOrderOnTop(false)
        // 预览置于普通图层，避免被系统合成层异常遮挡
        surfaceView.setZOrderMediaOverlay(false)

        // 设置SurfaceView的格式和类型，确保正确渲染
        surfaceHolder.setFormat(android.graphics.PixelFormat.RGBA_8888)
        surfaceHolder.setKeepScreenOn(true)

        // 确保SurfaceView可见并请求布局
        surfaceView.visibility = View.VISIBLE
        surfaceView.requestLayout()

        // 创建暂停覆盖层
        pauseOverlay = View(this)
        // 可以选择黑屏或自定义图片
        pauseOverlay.setBackgroundColor(android.graphics.Color.BLACK) // 黑屏
        // 如果要显示图片，可以使用以下代码：
        // pauseOverlay.setBackgroundResource(R.drawable.pause_image)
        pauseOverlay.visibility = View.GONE
        val overlayParams = FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
        )
        cameraContainer.addView(pauseOverlay, overlayParams)

        // 根据固定比例(16:9)调整Surface的实际缓冲区尺寸，避免拉伸
        surfaceView.addOnLayoutChangeListener { _, left, top, right, bottom, _, _, _, _ ->
            if (!isLiveStreaming) {
                val width = right - left
                val height = bottom - top
                adjustSurfaceFixedSize(width, height)
            }
        }

        // 延迟检查Surface状态，确保布局完成
        surfaceView.post {

            if (isLiveStreaming && pendingStartPush) {
                val surface = surfaceHolder.surface
                if (surface != null && surface.isValid) {
                    Log.d("ThreePaneLiveActivity", "Surface ready after layout, starting preview")
                    try {
                        mAlivcLivePusher.startPreview(surfaceView)
                        if (!mliveData?.pushLiveUrl.isNullOrEmpty()) {
                            mAlivcLivePusher.startPush(mliveData?.pushLiveUrl)
                        }
                        pendingStartPush = false
                    } catch (e: Exception) {
                        Log.e(
                            "ThreePaneLiveActivity",
                            "Error starting preview after layout: ${e.message}"
                        )
                    }
                }
            }
        }
        ivClose.setOnClickListener {
            if (currentState == State.NO_START_LIVE || currentState == State.LIVE_ENDED) {
                val intent = Intent(this@ThreePaneLiveActivity, LoginActivity::class.java)
                startActivity(intent)
                UserManager.clearData()
                finish()
            } else {
                DialogUtils.showEndLiveMuteConfirmDialog(this@ThreePaneLiveActivity) {
                    // 在后台线程执行结束直播操作
                    CoroutineScope(Dispatchers.IO).launch {
                        viewMode.endLive()
                    }
                }
            }


        }
        viewMode.EndLiveLV.observe(this@ThreePaneLiveActivity) {
            getLiveInfo()
        }
        // 初始不主动开播，由白板触发
        viewMode.LiveInfoLV.observe(this@ThreePaneLiveActivity) {
            if (it != null) {
                viewMode.liveUserCount(it.id.toString())
                //获取直播间历史评论
                mliveData = it
//                直播状态 0:未开始, 1:直播中, 2:已结束
                when (it.useState) {
                    0 -> {
                        tvLiveStatus.text = "未开始"
                        currentState = State.NO_START_LIVE
                        updateUIForState(currentState)
                    }

                    1 -> {
                        currentState = State.PRE_LIVE
                        updateUIForState(currentState)
                        if (startOnNextLiveInfo) {
                            startOnNextLiveInfo = false
                        startLiveStream()
                        }
                        tvLiveStatus.text = "直播中"

                    }

                    2 -> {
                        tvLiveStatus.text = "已结束"

                        currentState = State.LIVE_ENDED
                        updateUIForState(currentState)
                    }
                }
                // 处理风险提示文本 - 优先使用 riskAlertContent
                var riskContent: String? = null
                // 首先尝试从 riskAlertContent 获取
                riskContent = it.riskAlertContent as? String
                // 如果 riskAlertContent 为空，尝试从 liveCommonConfig 中获取
                if (riskContent.isNullOrEmpty() && it.liveCommonConfig != null) {
                    try {
                        val configStr = it.liveCommonConfig.toString()
                        // 尝试解析为 JSON
                        val jsonObject = org.json.JSONObject(configStr)
                        riskContent = jsonObject.optString("riskAlertContent")
                    } catch (e: Exception) {
                    }
                }

                // 如果还是没有，尝试从 liveConfig 中获取
                if (riskContent.isNullOrEmpty()) {
                    riskContent = it.liveConfig?.riskAlertContent
                    Log.d("RiskAlert", "riskContent from liveConfig: $riskContent")
                }


                if (riskContent != null && riskContent.isNotEmpty()) {
                    riskAlertText = riskContent
                } else {
                    // 如果没有风险内容，使用测试文本
                    riskAlertText =
                        "第一行：这是默认测试文本\n第二行：用于验证多行滚动效果\n第三行：请长按美颜按钮测试更多功能"
                }

                // 应用 liveCommonConfig 中的配置
                if (it.liveCommonConfig != null) {
                    try {
                        // 使用反射获取 liveCommonConfig 对象的属性
                        val configClass = it.liveCommonConfig.javaClass
                        Log.d("RiskAlert", "liveCommonConfig class: ${configClass.simpleName}")

                        // 获取 displayMode
                        val displayModeField = configClass.getDeclaredField("displayMode")
                        displayModeField.isAccessible = true
                        val modeValue = displayModeField.get(it.liveCommonConfig)
                        displayMode = (modeValue as? Number)?.toInt() ?: 2
                        Log.d("RiskAlert", "Set displayMode from liveCommonConfig: $displayMode")

                        // 获取 displayFontSize
                        val fontSizeField = configClass.getDeclaredField("displayFontSize")
                        fontSizeField.isAccessible = true
                        val fontSizeValue = fontSizeField.get(it.liveCommonConfig)
                        displayFontSize = (fontSizeValue as? Number)?.toFloat() ?: 16f
                        Log.d(
                            "RiskAlert",
                            "Set displayFontSize from liveCommonConfig: $displayFontSize"
                        )

                        // 获取 displayFontColour
                        val fontColourField = configClass.getDeclaredField("displayFontColour")
                        fontColourField.isAccessible = true
                        val fontColourValue = fontColourField.get(it.liveCommonConfig)
                        displayFontColour = fontColourValue as? String ?: "#FFFFFF"
                        Log.d(
                            "RiskAlert",
                            "Set displayFontColour from liveCommonConfig: $displayFontColour"
                        )

                        // 获取 displayScrollSpeed
                        val scrollSpeedField = configClass.getDeclaredField("displayScrollSpeed")
                        scrollSpeedField.isAccessible = true
                        val scrollSpeedValue = scrollSpeedField.get(it.liveCommonConfig)
                        displayScrollSpeed = (scrollSpeedValue as? Number)?.toInt() ?: 50
                        Log.d(
                            "RiskAlert",
                            "Set displayScrollSpeed from liveCommonConfig: $displayScrollSpeed"
                        )

                        // 获取 displayTransparency
                        val transparencyField = configClass.getDeclaredField("displayTransparency")
                        transparencyField.isAccessible = true
                        val transparencyValue = transparencyField.get(it.liveCommonConfig)
                        displayTransparency =
                            (transparencyValue as? Number)?.toFloat()?.div(100f) ?: 0.8f
                        Log.d(
                            "RiskAlert",
                            "Set displayTransparency from liveCommonConfig: $displayTransparency"
                        )

                    } catch (e: Exception) {
                        Log.d(
                            "RiskAlert", "Failed to get liveCommonConfig properties: ${e.message}"
                        )
                    }
                }

                // 确保 displayMode 是有效值
                if (displayMode != 1 && displayMode != 2) {
                    displayMode = 2 // 默认使用全屏滚动模式
                }

                // 如果 liveCommonConfig 中没有配置，尝试从 liveConfig 中获取
                if (displayMode == 1 && displayFontSize == 16f && displayFontColour == "#FFFFFF") {
                    it.liveConfig?.let { liveConfig ->
                        liveConfig.displayMode?.let { mode ->
                            displayMode = mode
                        }
                        liveConfig.displayFontSize?.let { size ->
                            displayFontSize = size.toFloat()
                        }
                        liveConfig.displayFontColour?.let { color ->
                            displayFontColour = color
                        }
                        liveConfig.displayScrollSpeed?.let { speed ->
                            displayScrollSpeed = speed
                        }
                        liveConfig.displayTransparency?.let { transparency ->
                            displayTransparency = transparency / 100f
                        }
                    }
                }

                updateRiskAlertDisplay()
            }

            setupMqtt()
            // 避免在刚拿到直播信息时强制重建 Surface，先按当前 Surface 启动预览
        }
        if (!checkCameraPermission()) requestCameraPermission()

        //获取直播回放详细信息
        viewMode.ReplayLV.observe(this@ThreePaneLiveActivity) {
            if (it != null) {
                try {

                    // 停止摄像头预览，显示视频
            setExternalVideoSourceEnabled(true)
                    ensureVideoView()
                    videoView?.visibility = View.VISIBLE
            surfaceView.visibility = View.GONE
            prepareAndStartMediaPlayer(it.liveReplayUrl.toUri())
                } catch (_: Exception) {
                }
            }
        }
        //获取课程内容（视频管理）详细信息
        viewMode.ContentLV.observe(this@ThreePaneLiveActivity) {
            if (it != null) {
                    try {

                        // 停止摄像头预览，显示视频
                        setExternalVideoSourceEnabled(true)
                    ensureVideoView()
                    videoView?.visibility = View.VISIBLE
                        surfaceView.visibility = View.GONE
                        prepareAndStartMediaPlayer(it.fileUrl.toUri())
                    } catch (_: Exception) {
                    }
                }
            }
        }

    // 供白板触发：请求下一次 LiveInfo 到达时启动直播
    fun triggerStartFromWhiteboard() {
        startOnNextLiveInfo = true
        getLiveInfo()
    }
    fun endLive() {
        currentState = State.LIVE_ENDED
        updateUIForState(currentState)
        val intent = Intent(this@ThreePaneLiveActivity, LoginActivity::class.java)
        startActivity(intent)
        UserManager.clearData()
        finish()
    }


    fun setLikeNumber(number: String) {
        tvStreamerNumber.text = number + "点赞"

    }

    private fun adjustSurfaceFixedSize(viewWidth: Int, viewHeight: Int) {
        if (viewWidth <= 0 || viewHeight <= 0) return

        // 获取摄像头支持的预览尺寸
        val cameraManager =
            getSystemService(Context.CAMERA_SERVICE) as android.hardware.camera2.CameraManager
        val cameraId = "1" // 默认前置摄像头

        try {
            val characteristics = cameraManager.getCameraCharacteristics(cameraId)
            val map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)

            if (map != null) {
                val previewSizes = map.getOutputSizes(android.graphics.SurfaceTexture::class.java)
                if (previewSizes.isNotEmpty()) {
                    // 选择最接近16:9比例的预览尺寸
                    val targetRatio = 16f / 9f
                    var bestSize = previewSizes[0]
                    var minDiff = Float.MAX_VALUE

                    for (size in previewSizes) {
                        val ratio = size.width.toFloat() / size.height.toFloat()
                        val diff = Math.abs(ratio - targetRatio)
                        if (diff < minDiff) {
                            minDiff = diff
                            bestSize = size
                        }
                    }

                    // 使用选中的预览尺寸设置Surface
                    try {
                        surfaceHolder.setFixedSize(bestSize.width, bestSize.height)
                        Log.d("Camera", "Set surface size: ${bestSize.width}x${bestSize.height}")
                        return
                    } catch (e: Exception) {
                        Log.e("Camera", "Failed to set surface size: ${e.message}")
                    }
                }
            }
        } catch (e: Exception) {
            Log.e("Camera", "Error getting camera characteristics: ${e.message}")
        }

        // 如果无法获取摄像头预览尺寸，使用默认的16:9比例计算
        val targetRatio = 16f / 9f
        val viewRatio = viewWidth.toFloat() / viewHeight.toFloat()

        var bufferWidth: Int
        var bufferHeight: Int
        if (viewRatio > targetRatio) {
            // 视图更"宽"，以高度为基准计算宽度
            bufferHeight = viewHeight
            bufferWidth = (bufferHeight * targetRatio).toInt()
        } else {
            // 视图更"高"，以宽度为基准计算高度
            bufferWidth = viewWidth
            bufferHeight = (bufferWidth / targetRatio).toInt()
        }

        if (bufferWidth > 0 && bufferHeight > 0) {
            try {
                surfaceHolder.setFixedSize(bufferWidth, bufferHeight)
                Log.d("Camera", "Set fallback surface size: ${bufferWidth}x${bufferHeight}")
            } catch (e: Exception) {
                Log.e("Camera", "Failed to set fallback surface size: ${e.message}")
            }
        }
    }

    private fun updateUIForState(state: State) {
        when (state) {
            State.NO_START_LIVE -> {
                // 显示开播前的UI
                userInfo.visibility = View.VISIBLE
                llLiveNotice.visibility = View.VISIBLE
                cameraContainer.visibility = View.VISIBLE
                tvMessage.text = "直播还未开播"
            }

            State.PRE_LIVE -> {
                // 显示开播前的UI
                userInfo.visibility = View.VISIBLE
                llLiveNotice.visibility = View.VISIBLE
                cameraContainer.visibility = View.VISIBLE

                // 隐藏结束状态的UI
                centerEndedContent.visibility = View.GONE
            }

            State.LIVE_ENDED -> {
                // 隐藏开播前的UI
                llLiveNotice.visibility = View.GONE
                userInfo.visibility = View.GONE
                llLiveNotice.visibility = View.GONE
                cameraContainer.visibility = View.GONE

                // 显示结束状态的UI
                centerEndedContent.visibility = View.VISIBLE
            }
        }
//        endLiveStream()
    }

    fun setLiveMute(isChecked: Boolean) {
        mAlivcLivePusher.setMute(isChecked)
        if (isChecked) {
            mAlivcLivePusher.setCaptureVolume(0)

        } else {
            mAlivcLivePusher.setCaptureVolume(100)

        }
    }

     fun startLiveStream() {
        try {
            Log.d("ThreePaneLiveActivity", "startLiveStream called")
            // 检查摄像头权限
            if (!checkCameraPermission()) {
                requestCameraPermission()
                return
            }
            // 检查麦克风权限
            if (!checkMicrophonePermission()) {
                requestCameraPermission()
                return
            }

            // 检查摄像头开关状态，如果关闭则显示背景
            if (!isCameraEnabled) {
                cameraOffBackground.visibility = View.VISIBLE
            }

            // 初始化推流器（只初始化一次）
            if (!isLiveStreaming) {
            mAlivcLivePusher.init(this@ThreePaneLiveActivity, mAlivcLivePushConfig)
            isLiveStreaming = true
            }

            // 检查Surface状态

            val surface = surfaceHolder.surface
            if (surface == null || !surface.isValid) {
                // Surface 未就绪，等待 surfaceCreated 再启动
                pendingStartPush = true
                return
            }

            // 保证相机源，先预览后推流
            setExternalVideoSourceEnabled(false)
            try {
                Log.d("ThreePaneLiveActivity", "Calling startPreview(startLiveStream)")
            mAlivcLivePusher.startPreview(surfaceView)
            } catch (_: Exception) {
            }
            surfaceView.postDelayed({
                try {
                    if (!mliveData?.pushLiveUrl.isNullOrEmpty()) {
                        if (!isLiveStreaming) {
                            Log.d("ThreePaneLiveActivity", "Calling startPush(startLiveStream)")
                    mAlivcLivePusher.startPush(mliveData?.pushLiveUrl)
                        }
                        Log.d("ThreePaneLiveActivity", "Push ensured")
                    }
                } catch (_: Exception) {
                }
            }, 200)

            // 再次踢醒本地预览，避免只推流不渲染本地
            surfaceView.postDelayed({
                kickPreview()
            }, 450)

            // 最后一手：延迟重建 Surface，清理冻结帧的根源（不影响正在推流）
            surfaceView.postDelayed({
                Log.d("ThreePaneLiveActivity", "Delayed rebuildPreviewSurface() after push")
                rebuildPreviewSurface()
            }, 800)

        } catch (e: Exception) {
            Log.e("ThreePaneLiveActivity", "Error in startLiveStream: ${e.message}")
            e.printStackTrace()
            Toast.makeText(this, "开启直播失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }


    private fun checkCameraPermission(): Boolean = ContextCompat.checkSelfPermission(
        this, Manifest.permission.CAMERA
    ) == PackageManager.PERMISSION_GRANTED

    private fun checkMicrophonePermission(): Boolean {
        return ContextCompat.checkSelfPermission(
            this, Manifest.permission.RECORD_AUDIO
        ) == PackageManager.PERMISSION_GRANTED
    }

    private fun requestCameraPermission() {
        ActivityCompat.requestPermissions(
            this,
            arrayOf(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO),
            CAMERA_PERMISSION_REQUEST
        )
    }

    fun openCamera(isChecked: Boolean) {
            if (isLiveStreaming) {
                if (isChecked) {
                // 恢复摄像头预览和推流
                // 确保预览已启动
                val surface = surfaceHolder.surface
                if (surface != null && surface.isValid) {
                    mAlivcLivePusher.startPreview(surfaceView)
                } else {
                    pendingStartPush = true
                }
                // 恢复推流
                mAlivcLivePusher.resume()
                // 更新状态并隐藏暂停覆盖层
                        isCameraEnabled = true
                pauseOverlay.visibility = View.GONE
                        cameraOffBackground.visibility = View.GONE

                } else {
                // 暂停摄像头预览和推流
                // 暂停推流（保持预览但停止推流）
                mAlivcLivePusher.pause()
                // 更新状态并显示暂停覆盖层
                        isCameraEnabled = false
                pauseOverlay.visibility = View.VISIBLE
                        cameraOffBackground.visibility = View.VISIBLE

                }
            } else {
                Toast.makeText(this, "请先开始直播", Toast.LENGTH_SHORT).show()
                Log.w("LiveStreamActivity", "Cannot control camera: not live streaming")
            }

    }
    // Expose camera switch to fragments
    /**
     * 摄像头切换
     */
    fun switchCamera(cameraId: String) {
        // 简化逻辑，按 LiveVideoFragment 的方式：切换后重绑预览
        mAlivcLivePusher.switchCamera()
    }


    /**
     * 从其他Activity返回时恢复摄像头
     */
    fun resumeCameraFromNavigation() {
        try {
            Log.d("ThreePaneLiveActivity", "Resuming camera from navigation")
            if (isLiveStreaming && checkCameraPermission() && isCameraEnabled) {
                val surface = surfaceHolder.surface
                if (surface != null && surface.isValid) {
                    // 恢复摄像头预览
                    mAlivcLivePusher.startPreview(surfaceView)
                    if (!mliveData?.pushLiveUrl.isNullOrEmpty()) {
                        surfaceView.postDelayed({
                            try {
                                mAlivcLivePusher.startPush(mliveData?.pushLiveUrl)
                            } catch (_: Exception) {
                            }
                        }, 150)
                    }
                }
            }
        } catch (e: Exception) {
            Log.e("ThreePaneLiveActivity", "Error resuming camera from navigation: ${e.message}")
        }
    }


    // ========== Local video playback control ==========
    fun pickLocalVideoAndRefresh(dialog: BottomSheetDialog) {
        // 打开系统相册选择视频
        val intent =
            Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI)
        intent.type = "video/*"
        if (intent.resolveActivity(packageManager) != null) {
            startActivityForResult(intent, 992)
        } else {
            ToastUtil.toastShortMessage("没有找到可用的相册应用")
        }
    }

    override fun onActivityResult(
        requestCode: Int, resultCode: Int, data: android.content.Intent?
    ) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 991 && resultCode == RESULT_OK && data?.data != null) {
            val uri = data.data!!
            contentResolver.takePersistableUriPermission(
                uri, android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION
            )
            val name = uri.lastPathSegment ?: "video_${System.currentTimeMillis()}"
            com.streamer.app.utils.BottomSheetUtils.addLocalVideo(this, name, uri.toString())
            // 下次打开弹窗会刷新；这里可提示
            android.widget.Toast.makeText(this, "已添加: $name", android.widget.Toast.LENGTH_SHORT)
                .show()
            com.streamer.app.utils.BottomSheetUtils.refreshLocalPlayList()
//            playLocalVideo(uri)
        } else if (requestCode == 992 && resultCode == RESULT_OK && data?.data != null) {
            val uri = data.data!!
            val name = uri.lastPathSegment ?: "video_${System.currentTimeMillis()}"
            com.streamer.app.utils.BottomSheetUtils.addLocalVideo(this, name, uri.toString())
            android.widget.Toast.makeText(this, "已添加: $name", android.widget.Toast.LENGTH_SHORT)
                .show()
            com.streamer.app.utils.BottomSheetUtils.refreshLocalPlayList()
            // 立刻播放并切换到视频
//            playLocalVideo(uri)
        }
    }

    fun playLocalVideo(uri: Uri) {
        try {
            // 停止摄像头预览，显示视频
            setExternalVideoSourceEnabled(true)
            ensureVideoView()
            videoView?.visibility = View.VISIBLE
            surfaceView.visibility = View.GONE
            prepareAndStartMediaPlayer(uri)
        } catch (_: Exception) {
        }
    }

    fun playSteamVideo(uri: Item) {
        try {
            if (uri.type == 1) {
             viewMode.replay(uri.id)
            } else {
                viewMode.content(uri.id)

            }
        } catch (_: Exception) {
        }
    }

    fun showCameraPreview() {
        try {
            stopVideoPlaybackIfAny()
            surfaceView.visibility = View.VISIBLE
            videoView?.visibility = View.GONE
            setExternalVideoSourceEnabled(false)
            openCamera(true)
        } catch (_: Exception) {
        }
    }

    private fun ensureVideoView() {
        if (videoView == null) {
            videoView = VideoView(this)
            val lp = FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
            )
            lp.gravity = android.view.Gravity.CENTER
            videoView?.layoutParams = lp
            cameraContainer.addView(videoView)
        }
    }

    private fun prepareAndStartMediaPlayer(uri: Uri) {
        try {
            if (videoView != null) {
                videoView?.setVideoURI(uri)
                videoView?.setOnPreparedListener { mediaPlayer ->
                    mediaPlayer.start()
                    updateLocalPlayProgressUI(mediaPlayer.duration)
                startProgressUpdater()
            }
                videoView?.start()
            }
        } catch (e: Exception) {
            // 处理异常，例如显示错误提示
            Log.e("VideoView", "Error preparing VideoView", e)
        }
    }


    private fun updateLocalPlayProgressUI(totalMs: Int) {
        val dialog = com.streamer.app.utils.BottomSheetUtils.getLastLocalPlayDialog() ?: return
        val view = dialog.findViewById<View>(android.R.id.content) ?: return
        val seekBar = view.findViewById<android.widget.SeekBar>(R.id.seekbar_progress) ?: return
        val tvCurrent = view.findViewById<TextView>(R.id.tv_current_time) ?: return
        val tvTotal = view.findViewById<TextView>(R.id.tv_total_time) ?: return

        seekBar.max = totalMs
        tvTotal.text = formatTime(totalMs)
        // 初始当前时间
        tvCurrent.text = formatTime(videoView?.currentPosition ?: 0)

        seekBar.setOnSeekBarChangeListener(object : android.widget.SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(
                seekBar: android.widget.SeekBar?, progress: Int, fromUser: Boolean
            ) {
                if (fromUser) videoView?.seekTo(progress)
            }

            override fun onStartTrackingTouch(seekBar: android.widget.SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: android.widget.SeekBar?) {}
        })
    }

    private fun startProgressUpdater() {
        val dialog = com.streamer.app.utils.BottomSheetUtils.getLastLocalPlayDialog() ?: return
        val view = dialog.findViewById<View>(android.R.id.content) ?: return
        val seekBar = view.findViewById<android.widget.SeekBar>(R.id.seekbar_progress) ?: return
        val tvCurrent = view.findViewById<TextView>(R.id.tv_current_time) ?: return
        val handler = android.os.Handler(mainLooper)
        val r = object : Runnable {
            override fun run() {
                val pos = videoView?.currentPosition ?: 0
                seekBar.progress = pos
                tvCurrent.text = formatTime(pos)
                if (videoView?.visibility == View.VISIBLE) handler.postDelayed(this, 500)
            }
        }
        handler.post(r)
    }



    private fun setExternalVideoSourceEnabled(enable: Boolean) {
        try {
            val method = mAlivcLivePusher.javaClass.getMethod(
                "setExternalVideoSource",
                Boolean::class.javaPrimitiveType,
                Boolean::class.javaPrimitiveType,
                Boolean::class.javaPrimitiveType
            )
            method.invoke(mAlivcLivePusher, enable, true, true)
        } catch (_: Exception) {
        }
    }

    private fun stopVideoPlaybackIfAny() {
        try {
            // Stop legacy VideoView if used
            videoView?.stopPlayback()
            videoView?.visibility = View.GONE
            // Stop and release MediaPlayer + hide TextureView
            mediaPlayer?.let { mp ->
                try {
                    mp.stop()
                } catch (_: Exception) {
                }
                try {
                    mp.reset()
                } catch (_: Exception) {
                }
                try {
                    mp.release()
                } catch (_: Exception) {
                }
            }
            mediaPlayer = null
        } catch (_: Exception) {
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int, permissions: Array<out String>, grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == CAMERA_PERMISSION_REQUEST) {
            val grantedAll =
                grantResults.isNotEmpty() && grantResults.all { it == PackageManager.PERMISSION_GRANTED }
            if (!grantedAll) {
                Toast.makeText(this, "需要摄像头权限才能开启直播", Toast.LENGTH_SHORT).show()
                return
            }
            // 权限已授予，若存在等待启动则触发
                try {
                    mAlivcLivePusher.startPreview(surfaceView)
                    if (!mliveData?.pushLiveUrl.isNullOrEmpty()) {
                        surfaceView.postDelayed({
                            try {
                                mAlivcLivePusher.startPush(mliveData?.pushLiveUrl)
                            } catch (_: Exception) {
                            }
                        }, 150)
                    }
                } catch (_: Exception) {
                } finally {
                    pendingStartPush = false
                }
        }
    }


    override fun onPause() {
        super.onPause()
        try {
            // 暂停推流当Activity暂停时
            if (isLiveStreaming) {
                Log.d("ThreePaneLiveActivity", "Activity paused, pausing push")
                mAlivcLivePusher.pause()
                // 安全停止预览以避免BufferQueue错误
                safeStopPreview()
            }
        } catch (e: Exception) {
            Log.e("ThreePaneLiveActivity", "Error pausing camera: ${e.message}")
        }
    }

    override fun onResume() {
        super.onResume()
        try {
            // Resume camera preview when activity is resumed
            Log.d("ThreePaneLiveActivity", "Activity resumed, checking camera state")
            if (isLiveStreaming && checkCameraPermission()) {
                // 确保外部源关闭，恢复相机预览/推流
                ensureCameraPreviewActive()
            }
        } catch (e: Exception) {
            Log.e("ThreePaneLiveActivity", "Error resuming camera: ${e.message}")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        try {
            if (isLiveStreaming) {
                Log.d("ThreePaneLiveActivity", "Activity destroyed, stopping preview and push")
                // 停止预览和推流
                mAlivcLivePusher.stopPreview()
                mAlivcLivePusher.stopPush()
                // 销毁推流器
                mAlivcLivePusher.destroy()
                isLiveStreaming = false
            }
        } catch (e: Exception) {
            Log.e("ThreePaneLiveActivity", "Error in onDestroy: ${e.message}")
        }
    }

    fun getLiveInfo() {
        viewMode.getLiveInfo()
    }

    /**
     * 强制刷新SurfaceView以确保画面正常显示
     */
    // refreshSurfaceView 已不再需要，移除以精简逻辑

    /**
     * 安全地停止预览，避免BufferQueue错误
     */
    private fun safeStopPreview() {
        try {
            if (isLiveStreaming) {
                mAlivcLivePusher.stopPreview()
                Log.d("ThreePaneLiveActivity", "Preview stopped safely")
            }
        } catch (e: Exception) {
            Log.e("ThreePaneLiveActivity", "Error stopping preview safely: ${e.message}")
        }
    }

    // 统一的预览恢复方法：确保相机源、层级、预览与推流恢复
    private fun ensureCameraPreviewActive() {
        try {
            // 关闭外部视频源，回到相机
            setExternalVideoSourceEnabled(false)
            // UI 图层恢复
            stopVideoPlaybackIfAny()
            surfaceView.visibility = View.VISIBLE
            pauseOverlay.visibility = View.GONE
            videoView?.visibility = View.GONE
            // 让相机在底层渲染，由上层控件覆盖

                val surface = surfaceHolder.surface
                if (surface != null && surface.isValid) {
                try {
                    mAlivcLivePusher.startPreview(surfaceView)
                } catch (_: Exception) {
                }
                if (isCameraEnabled) {
                    try {
                        mAlivcLivePusher.resume()
                    } catch (_: Exception) {
                    }
                }
                // 轻踢醒
                surfaceView.postDelayed({ kickPreview() }, 300)
            } else {
                pendingStartPush = true
            }
        } catch (_: Exception) {
        }
    }

    // 轻踢醒：重启预览，清理本地合成管线中的“冻结帧”
    private fun kickPreview() {
        try {
            setExternalVideoSourceEnabled(false)
            Log.d("ThreePaneLiveActivity", "kickPreview(): stopPreview -> startPreview -> resume")
            mAlivcLivePusher.stopPreview()
            Log.d("ThreePaneLiveActivity", "kickPreview(): startPreview")
            mAlivcLivePusher.startPreview(surfaceView)
            if (isCameraEnabled) {
                try {
                    mAlivcLivePusher.resume()
                } catch (_: Exception) {
                }
            }
        } catch (_: Exception) {
        }
    }

    // 当本地预览疑似卡帧时，重建 SurfaceView 强制让 SDK 绑定新的 Surface
    private fun rebuildPreviewSurface() {
        try {
            // 移除旧的 SurfaceView
            try {
                cameraContainer.removeView(surfaceView)
            } catch (_: Exception) {
            }
            // 新建 SurfaceView 并替换引用
            val newSurface = SurfaceView(this)
            val newHolder = newSurface.holder
            newHolder.setFormat(android.graphics.PixelFormat.RGBA_8888)
            newHolder.setKeepScreenOn(true)
            val lp = FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
            )
            lp.gravity = Gravity.CENTER
            newSurface.layoutParams = lp
            newSurface.setZOrderOnTop(false)
            newSurface.setZOrderMediaOverlay(false)

            // 绑定回调：若 pendingStartPush 或 Surface 有效，启动预览/推流
            newHolder.addCallback(object : SurfaceHolder.Callback {
                override fun surfaceCreated(holder: SurfaceHolder) {
                    try {
                        if (isLiveStreaming) {
                            mAlivcLivePusher.startPreview(newSurface)
                            if (isCameraEnabled) {
                                try {
                                    mAlivcLivePusher.resume()
                                } catch (_: Exception) {
                                }
                            }
                            pendingStartPush = false
                        }
                    } catch (_: Exception) {
                    }
                }

                override fun surfaceChanged(
                    holder: SurfaceHolder, format: Int, width: Int, height: Int
                ) {
                }

                override fun surfaceDestroyed(holder: SurfaceHolder) {
                    safeStopPreview()
                }
            })

            // 加入容器
            cameraContainer.addView(newSurface)

            // 更新引用
            surfaceView = newSurface
            surfaceHolder = newHolder

            // 确保预览激活
            ensureCameraPreviewActive()
        } catch (_: Exception) {
        }
    }

    private fun setupMqtt() {
        mqttManager = MqttManager.getInstance()
        mqttManager.addMessageCallback(this)

        val random6Digit = Random.nextInt(100000, 1000000)
        // 连接MQTT
        mqttManager.connect(
            this@ThreePaneLiveActivity,
            "${mliveData?.liveRoomNo + "," + mliveData?.id + "," + getLocalUser()?.id + ",5" + "," + random6Digit}"
        ) { success, message ->
            runOnUiThread {
                if (success) {
                    Log.d("LiveStreamActivity", "MQTT connected: $message")

                    // 订阅直播相关主题
                    subscribeToLiveTopics()
                } else {
                    Log.e("LiveStreamActivity", "MQTT connection failed: $message")

                }
            }
        }
    }

    private fun subscribeToLiveTopics() {
        // 订阅直播相关主题
        val liveRoomNo = mliveData?.id ?: ""
        val topics = listOf(
            "chat/$liveRoomNo"
        )

        topics.forEach { topic ->
            mqttManager.subscribe(topic) { success, message ->

            }
        }
    }

    override fun onMessageReceived(topic: String, message: String) {
        runOnUiThread {
            handleLiveMessage(message)
        }
    }

    override fun onConnectionStatusChanged(connected: Boolean) {
    }

    private fun handleLiveMessage(message: String) {
        try {
            val gson = Gson()
            val chatMessage = gson.fromJson(message, MessageBean::class.java)

            when (chatMessage.type) {
                1 -> { /* JOIN(1) - 进入房间 */
                }

                2 -> { /* LEAVE(2) - 离开房间 */
                }

                3 -> { // MSG(3) - 普通消息
                    // 添加到弹幕适配器


                }

                4 -> { /* SYSTEM(4) - 系统消息 */
                }

                5 -> { /* DRAW(5) - 抽奖倒计时 */
                }

                6 -> { /* COUPON(6) - 优惠券倒计时 */
                }

                7 -> { /* TAUGHT(7) - 商品讲解 */
                }

                8 -> { /* NOTICE(8) - 公告 */
                }

                9 -> { /* COUPON_RECEIVE(9) - 优惠券领取 */
                }

                10 -> { /* DRAW_USER(10) - 抽奖完成通知 */
                }

                11 -> { /* MSG_CONCEAL(11) - 消息隐藏 */
                }

                12 -> { /* BESTOW_GIFT(12) - 赠送礼物 */

                    Log.d("xxxx", "赠送礼物=====+$chatMessage")
                    llGift.visibility = View.VISIBLE
                    val gson = Gson()
                    val giftData = gson.fromJson(chatMessage.content, GiftData::class.java)
                    tvGiftName.text = giftData.nickName + "赠送了一个" + giftData.giftName
                    ivGiftIcon.apply {
                        Glide.with(this).load(giftData.effectUrl).into(this)
                    }
                    llGift.postDelayed({
                        llGift.visibility = View.GONE
                    }, 5000)
                }

                13 -> { /* DEFRIEND(13) - 踢出直播间 */
                }

                14 -> { /* POINTS_ACQUISITION(14) - 获取积分 */
                }

                15 -> { /* CANCEL_TAUGHT(15) - 取消讲解 */
                }

                16 -> { /* LIKE(16) - 点赞 */

                }

                17 -> { /* PUTAWAY(17) - 商品上架 */
                }

                18 -> { /* CONFIG_STATUS_UPDATE(18) - 直播配置状态更新 */
                }

                19 -> { /* THE_USER_IS_BUYING(19) - 正在购买商品 */
                }

                20 -> { /* POPULARITY(20) - 直播间人气推送 */

                }
                26->{
        viewMode.getLiveInfo()
    }
                else -> { /* 未知类型 */
                }
            }

        } catch (e: JsonSyntaxException) {
            Log.e("LiveStreamActivity", "Error parsing JSON message: ${e.message}")
            Log.e("LiveStreamActivity", "Raw message: $message")
        } catch (e: Exception) {
            Log.e("LiveStreamActivity", "Error handling message: ${e.message}")
            Log.e("LiveStreamActivity", "Raw message: $message")
        }
    }



    private fun updateRiskAlertDisplay() {


        riskAlertTextView.text = riskAlertText
        riskAlertTextView.textSize = displayFontSize
        riskAlertTextView.setTextColor(android.graphics.Color.parseColor(displayFontColour))
        riskAlertTextView.alpha = displayTransparency
        riskAlertTextView.visibility = View.VISIBLE


        riskAlertTextView.bringToFront()
        riskAlertTextView.elevation = 20f
        riskAlertTextView.visibility = View.VISIBLE


        // 清除可能影响 y 定位的顶部 margin（不依赖具体父布局类型）
        (riskAlertTextView.layoutParams as? ViewGroup.MarginLayoutParams)?.let { lp ->
            if (lp.topMargin != 0) {
                lp.topMargin = 0
                riskAlertTextView.layoutParams = lp
            }
        }

        // 根据显示模式启动滚动（强制按当前需求使用全屏行滚动）
        Log.d("RiskAlert", "=== 准备启动滚动，displayMode = $displayMode（强制按2处理） ===")
        when (displayMode) {
            1 -> {
                Log.d("RiskAlert", "Starting bottom scroll (单行循环滚动)")
                startBottomScroll()
            }

            2 -> {
                Log.d("RiskAlert", "Starting full screen scroll (5行滚动)")
                startFullScreenScroll()
            }

            else -> {
                // 强制全屏行滚动
                startFullScreenScroll()
            }
        }
    }

    private fun startBottomScroll() {
        stopRiskAlertScroll()
        riskAlertScrollJob = CoroutineScope(Dispatchers.Main).launch {
            val textView = riskAlertTextView
            val text = textView.text.toString()
            val textWidth = textView.paint.measureText(text)
            val screenWidth = textView.context.resources.displayMetrics.widthPixels



            // 调整滚动速度，确保不会太快
            val scrollSpeed = if (displayScrollSpeed < 10) 50 else displayScrollSpeed



            var currentX = -textWidth.toFloat() // 从左边开始

            while (isActive) {
                textView.translationX = currentX
                currentX += 1f // 每次移动1像素，从左往右

                if (currentX >= screenWidth) {
                    currentX = -textWidth.toFloat() // 回到左边重新开始
                    // 滚动完成后，停留一下再重新开始
                    delay(2000) // 停留2秒
                }

                delay(scrollSpeed.toLong())
            }
        }
    }

    private fun startFullScreenScroll() {
        stopRiskAlertScroll()
        riskAlertScrollJob = CoroutineScope(Dispatchers.Main).launch {
            val textView = riskAlertTextView
            val text = textView.text.toString()

            // 使用根布局高度，计算可容纳的“行数”（按 TextView 实际高度划分）
            val rootView = findViewById<View>(android.R.id.content)
            val containerHeight = (rootView.height.takeIf { it > 0 }
                ?: textView.context.resources.displayMetrics.heightPixels)

            // 确保拿到 TextView 的高度
            var tvHeight = textView.height
            if (tvHeight <= 0) {
                textView.measure(
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
                )
                tvHeight = textView.measuredHeight
            }
            if (tvHeight <= 0) {
                // 兜底：用字体大小粗略估算行高
                tvHeight = (displayFontSize * resources.displayMetrics.density * 1.8f).toInt()
                    .coerceAtLeast(1)
            }
            // 按需求固定分成5行显示，更符合期望效果
            val rows = 5
            val lineHeightPx = containerHeight / rows.toFloat()
            Log.d(
                "RiskAlert",
                "Full screen scroll started, containerHeight=$containerHeight, tvHeight=$tvHeight, rows=$rows, lineHeightPx=$lineHeightPx"
            )

            // 调整滚动速度
            val scrollSpeed = if (displayScrollSpeed < 10) 50 else displayScrollSpeed
            Log.d("RiskAlert", "Adjusted scroll speed: $scrollSpeed")

            var rowIndex = 0
            val screenWidth = textView.context.resources.displayMetrics.widthPixels

            while (isActive) {
                // 计算当前行的Y坐标（行中心对齐到该行区域中部）
                // 将 TextView 垂直居中到该行区域内
                val rowTop = rowIndex * lineHeightPx
                val centeredTop = (rowTop + (lineHeightPx - tvHeight) / 2f)
                val clampedY = centeredTop.coerceIn(
                    0f, (containerHeight - tvHeight).toFloat().coerceAtLeast(0f)
                )
                Log.d("RiskAlert", "=== 显示第${rowIndex + 1}/$rows 行，y=$clampedY ===")

                // 将 TextView 移到该行
                textView.y = clampedY
                textView.translationX = 0f

                // 计算文本宽度
                val textWidth = textView.paint.measureText(text)
                Log.d(
                    "RiskAlert",
                    "行${rowIndex + 1} - textWidth=$textWidth, screenWidth=$screenWidth"
                )

                // 水平滚动：从左完全外到右完全外
                var currentX = -textWidth.toFloat()
                val endX = screenWidth.toFloat()
                while (isActive && currentX < endX) {
                    textView.translationX = currentX
                    currentX += 1f
                    delay(scrollSpeed.toLong())
                }
                textView.translationX = 0f
                Log.d("RiskAlert", "行${rowIndex + 1} 滚动完成")

                // 切换到下一行；到达底部后回到顶部
                rowIndex = (rowIndex + 1) % rows
                delay(500)
            }
        }
    }

    private fun stopRiskAlertScroll() {
        riskAlertScrollJob?.cancel()
        riskAlertScrollJob = null
        riskAlertTextView.translationX = 0f
    }

}


